package br.com.news.ws;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import org.apache.log4j.Logger;

import br.com.news.utils.database.beans.NoticiaBean;
import br.com.news.utils.service.exception.ServiceException;

import com.google.gson.Gson;

@Path("/noticias")
public class NoticiaWs extends GenericWs<NoticiaBean> {

	private static final Logger logger = Logger.getLogger(NoticiaWs.class);
	
	@POST
	@Path("/insert")
	@Produces("application/json")
	@Consumes("application/json")
	public String save(String json) {
		Gson gson = new Gson();
		try {
			NoticiaBean noticia = (NoticiaBean) convertFromJson(json, new NoticiaBean());
			Long id = RmiFactory.getNoticiaService().save(noticia);
			return gson.toJson("Sucesso - noticia cadastrada id :"+id);
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
		}
		return gson.toJson("Falha ao cadastrar noticia!");
	}
	
	@POST
	@Path("/update")
	@Produces("application/json")
	@Consumes("application/json")
	public String update(String json) {
		Gson gson = new Gson();
		try {
			NoticiaBean noticia = (NoticiaBean) convertFromJson(json, new NoticiaBean());
			RmiFactory.getNoticiaService().update(noticia);
			return gson.toJson("Sucesso - noticia alterada id :" + noticia.getIdNoticia());
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
		}
		return gson.toJson("Falha ao alterar noticia!");
	}
	
	/**
	 * Retorna noticias a partir do idCategoria, com o id menor que idNoticia, ou, ser o idNoticia for 0,
	 * as ultimas, e a quantidade é definida pelo parametro qntNoticias.
	 * 
	 * @param qntNoticias
	 * @param idNoticia
	 * @param idCategoria
	 * @return String
	 */
	@GET
	@Path("/noticiasPorPagina/{qntNoticias}/{idNoticia}/{idCategoria}")
	public String lastNews(@PathParam(value="qntNoticias") int qntNoticias,@PathParam(value="idNoticia") long idNoticia,
			@PathParam(value="idCategoria") long idCategoria){
		try {
			return listToJson(RmiFactory.getNoticiaService().lastNews(qntNoticias, idNoticia, idCategoria));
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			return "NOK";
		}
	}
	
	/**
	 * Retorna noticias a para a categoria do idCategoria, com o id maior que idNoticia
	 * 
	 * @param idNoticia
	 * @param idCategoria
	 * @return String
	 */
	@GET
	@Path("/ultimasNoticias/{idNoticia}/{idCategoria}")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public String lastNews(@PathParam(value="idNoticia") long idNoticia, @PathParam(value="idCategoria") long idCategoria){
		try {
			return listToJson(RmiFactory.getNoticiaService().lastNews(idNoticia, idCategoria));
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			return "NOK";
		}
	}
	
	@GET
	@Path("/xml/last/news/{qntNoticias}/{idNoticia}/{idCategoria}")
	@Produces("application/xml")
	public List<NoticiaBean> lastNewsXml(@PathParam(value="qntNoticias") int qntNoticias,@PathParam(value="idNoticia") long idNoticia,
			@PathParam(value="idCategoria") long idCategoria){
		try {
			return RmiFactory.getNoticiaService().lastNews(qntNoticias, idNoticia, idCategoria);
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			return null;
		}
	}
	
	@GET
	@Path("/existeNoticia")
	@Produces("application/json")
	@Consumes("application/json")
	public String existeNoticia(NoticiaBean noticiaBean) {
		return booleanToJson(RmiFactory.getNoticiaService().existeNoticia(noticiaBean));
	}

	@GET
	@Path("/findAll")
	@Produces("application/json")
	public String findAll() {
		try {
			return listToJson(RmiFactory.getNoticiaService().findAll());
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			return "NOK";
		}
	}
	
	@GET
	@Path("/noticiaById/{idNoticia}")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public String findNoticiaById(@PathParam(value="idNoticia") Long idNoticia) {
		try {
			return toJson(RmiFactory.getNoticiaService().findNoticiaById(idNoticia));
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			return "NOK";
		}
	}
	
	@GET
	@Path("/imagemNoticia/{idNoticia}")
	@Produces("image/jpeg")
	public Response findImageByIdNoticia(@PathParam(value="idNoticia") Long idNoticia) {
		try {
			ResponseBuilder response = Response.ok((Object) RmiFactory.getNoticiaService().findImageByIdNoticia(idNoticia).getArquivoImagem());
	        return response.build();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			 ResponseBuilder response = Response.status(Status.NOT_FOUND);
	         return response.build();
		}
	}
	
	@GET
	@Path("/quantidadePaginas/{idCategoria}")
	public String quantidadePaginas(@PathParam("idCategoria") long idCategoria) {
		return toJson(RmiFactory.getNoticiaService().quantidadePaginas(idCategoria));
	}
	
	/**
	 * Retorna noticias a partir do idCategoria, com o id menor que idNoticia, ou, ser o idNoticia for 0,
	 * as ultimas, e a quantidade é definida pelo parametro qntNoticias.
	 * 
	 * @param qntNoticias
	 * @param idNoticia
	 * @param idCategoria
	 * @return String
	 */
	@GET
	@Path("/noticiasByPagina/{linha}/{idCategoria}/{quantidade}")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public String lastNews(@PathParam(value="linha") int linha,@PathParam(value="idCategoria") long idCategoria,
			@PathParam(value="quantidade") int quantidade){
			return listToJson(RmiFactory.getNoticiaService().findNoticiasPorPagina(linha, idCategoria, quantidade));
	}
	
	@GET
	@Path("/noticiaPorNome/{linha}")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public String buscaNoticiaPorNome(@PathParam(value="linha") String nome) {
		return listToJson(RmiFactory.getNoticiaService().buscaNoticiaPorNome(nome));
	}
	
	@POST
	@Path("/findByExample")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes("application/json")
	public String findByExample(String noticia) {
		NoticiaBean noticiaBean = (NoticiaBean) convertFromJson(noticia, new NoticiaBean());
		return  listToJson(RmiFactory.getNoticiaService().findByExample(noticiaBean));
	}
	
	@GET
	@Path("/returnTextNew/{idNoticia}/")
	public String returnTextNew(@PathParam(value="idNoticia") long idNoticia){
		try {
			return RmiFactory.getNoticiaService().returnTextNew(idNoticia);
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			return "NOK";
		}
	}
}
